package com.tn.auth.utils;

import com.tn.auth.vo.TokenVO;
import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 认证信息工具类
 *
 * @program: tn_aucy_java
 * @author: yangjiayao
 * @create: 2021/12/22
 */
public class TokenUtil {
    /**
     * token参数名
     */
    public static final String TOKEN_PARAM_NAME = "token";

    /**
     * 用户
     */
    public static final String USER_PARAM_NAME = "user";

    /**
     * token列表
     */
    public static ConcurrentMap<String, TokenVO> tokenList = new ConcurrentHashMap<>();

    /**
     * 添加token
     *
     * @param user 用户
     * @return token
     */
    public static String addToken(Integer user) {
        long grantTime = System.currentTimeMillis();
        String token =
                DigestUtils.md5DigestAsHex((String.valueOf(user) + grantTime + (int) (Math.random() * 10)).getBytes());
        TokenUtil.tokenList.put(String.valueOf(user), new TokenVO(token, grantTime));
        return token;
    }

    /**
     * 封装token信息
     *
     * @param responseParam 参数
     * @param user          用户
     */
    public static void addTokenInfo(Map<String, Object> responseParam, Integer user) {
        String token = TokenUtil.addToken(user);
        responseParam.put("tokenParamValue", token);
        responseParam.put("tokenParamName", TokenUtil.TOKEN_PARAM_NAME);
        responseParam.put("userParamName", TokenUtil.USER_PARAM_NAME);
        responseParam.put("userParamValue", user);
    }
}
